<?php

namespace app\controller;

use app\BaseController;
use app\Request;
use app\service\BigService;
use app\service\BigServiceRush;
use app\service\ImageService;
use app\util\Tool;
use mysql_xdevapi\Exception;
use think\facade\Config;
use think\facade\Log;
use think\Response;

class IndexRush extends BaseController
{
    protected $bigServiec_rush;
    protected $r; //Request 对象

    protected $bigservice;

    protected $imageService;

    public function __construct(BigServiceRush $bigServiec_rush, Request $r, BigService $xman1, ImageService $imageService)
    {
        $this->bigServiec_rush = $bigServiec_rush;
        $this->r = $r;
        $this->bigservice = $xman1;
        $this->imageService = $imageService;
    }

    public function index()
        //https://www.kancloud.cn/a173512/thinkphp6/1327360
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#bc70ec;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">16载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }


    //抢购的临时写这个项目。
    public function findRecordByxx_rush(Request $request)
    {
        $xx = $request->get("xx");
        $arr = $this->bigServiec_rush->findRecordByxx_rush($xx);
        return json_encode($arr);
    }

    //findOrderBytid2_rush
    public function findOrderBytid2_rush(Request $request)
    {
        $tid2 = $request->get("tid2");
        $arr = $this->bigServiec_rush->findOrderBytid2_rush($tid2);
        return json_encode($arr);
    }

    public function getneworder_rush(Request $request)
    {
        $tid2 = $request->get("tid2"); //222
//        $dytid2 = $request->get("tid2"); //222
//        $tid2 = substr($tid2, 1);
        $test = $request->get("test"); //222
        $paytype = $request->get("paytype", 999);
        $okfee = $request->get('okfree');

        if ($okfee == 'yes') {
            $shortorderid = $request->get('shortorderid');
            $arr1 = $this->bigServiec_rush->findOrderByShortid_rush($shortorderid);
            //return json_encode($arr1);
            //根据短的订单号来查订单
            $dytid2 = '3'; //丢了 用sn合适不
            $detailid = $shortorderid;
            $refund_fee = 0;
            //return json_encode($arr1);
        } else {
            $tid23 = $request->get("tid2"); //222
            $dytid2 = $request->get("tid2"); //222
            $tid23 = substr($tid23, 1);
            $arr1 = $this->bigServiec_rush->findOrderBytid2_rush($tid23);
            $detailid = $arr1['detailid'];
            $refund_fee = $arr1['refundfee'];
        }


        if (empty($arr1)) {
            echo 'no data1';
            return 'no data';
        } else {
            //return json_encode($arr1);
        }


        $uniacid = $arr1['uniacid'];
        $themeid = $arr1['themeid'];
        $theme_name = "--t--";
        try {
            $arr_theme = $this->bigServiec_rush->findThemebyid_rush($themeid);
            $theme_name = $arr_theme['title'];
        } catch (Exception $e) {
            // 处理其他可能的异常
            error_log("Unexpected error calculating profit for themeid {$themeid}: " . $e->getMessage());
            return 'short err and find theme null';
        }


        $avatar = $arr1['avatar'];
        $username = $arr1['username'];
        $nickname = $arr1['nickname'];
        $mobile = $arr1['mobile'];

        //return json_encode($arr1);

        $status_pay = $arr1['paystate'];


        // $refund_fee = $arr2['refund_fee'];  这个 抢购比较特别。拼团中取record 中的数据。但是抢购 要取订单的
        //id 就是 detailid
        //$arr2 = $this->bigServiec->findRecordByxx($detailid);
        //$refund_fee = $arr1['refundfee'];  //先取了; 先弄个空看能不能插入;

        //return json_encode($arr1);

        $arr2 = $this->bigServiec_rush->findRecordByxx_rush($detailid);

        //return json_encode($arr2);

        $status_pay = $arr2['status']; //改成这个

        $billcode = $arr2['billcode'];
        $openid = $arr2['openid'];
        $fee = $arr2['fee'];
        $option = $arr2['option'];
        $option2 = $arr2['option2'];

        $note = $arr2['address'];
        $note2 = $arr2['datetime'];
        $f_openid = $arr2['fopenid'];
        $status_refund = $arr2['isrefund'];

        $add_time = $arr2['addtime'];
        $add_time = date("Y-m-d H:i:s", $add_time);
        $pay_time = $arr2['paytime'];
        $pay_time = date("Y-m-d H:i:s", $pay_time);

        $status_type = 0; //硬塞

        $remark = $arr2['remark'];
        $source_openid = $arr2['sourceid'];
        $verify_time = $arr2['verifytime'];
        $verify_time = date("Y-m-d H:i:s", $verify_time);
        $verify_openid = $arr2['verifyopenid'];
        $birthday = $arr2['birthday'];
        $gender = $arr2['gender'];
        if ($gender == '男生') {
            $gender = 1;
        } else {
            $gender = 2;
        }
        $groups = $arr2['groups'];

        //5月11号新增
        if (999 == $paytype) {
            // 2025 6 8 前端打包后时必传的
            $r = $this->getpaychoicebypid($uniacid); //2  支付方式
        } else {
            $r = $paytype;
        }


        $mch_id = '';
        $api_v3_key = "";
        $mch_serial_number = "";
        $private_key = "";
        $apiclient_cert = "";
        $pubkey_id = "";
        $pubkey_pem = "";

        if (1 == $r) {
            $lg = "no"; //自收款 不做处理
            $bossphone = $this->findboss_rush($themeid);
            if ($bossphone == "") {
                Log::info("查boss没有查到：" . $themeid);
            } else {
                //findpaymsg($bossphone)
                $r = $this->findpaymsg($bossphone);
                if (empty($r)) {
                    //echo '数组为空';
                    Log::info("没找到支付信息：" . $bossphone);
                } else {
                    //echo '数组不为空';
                    //todo 组装支付数据
                    $mch_id = $r['mchId'];
                    $api_v3_key = $r['apiV3kEY'];
                    $private_key = $r['privateKey'];
                    $apiclient_cert = $r['apiclientCert'];
                    $mch_serial_number = $r['mchSerialNumber'];
                    $pubkey_id = $r['pubkeyId'];
                    $pubkey_pem = $r['pubkeyPem'];

                }
            }
        } else {
            $lg = "yes"; //老业务。 每日 秒 代理
        }
        $url = 'https://gateway.cmxz.com.cn/oa/api/new/order/';
        $params_a = [
            'lg' => $lg,
            'nid' => "2" . $detailid,
            'dytid2' => $dytid2,

            'uniac_id' => $uniacid,
            'ntheme_id' => "2" . $themeid,
            'theme_name' => $theme_name,
            "bill_code" => $billcode,
            "nickname" => $nickname,
            "avatar" => $avatar,
            "username" => $username,
            "mobile" => $mobile,
            "openid" => $openid,
            "fee" => $fee,
            "option" => $option,
            "option2" => $option2,

            "note" => $note,
            "note2" => $note2,
            "f_openid" => $f_openid,
            "status_refund" => $status_refund,
            "refund_fee" => $refund_fee,
            "status_pay" => $status_pay,

            "add_time" => $add_time,
            "pay_time" => $pay_time,

            "status_type" => $status_type, //身份
            "pid" => 0,
            "noid" => 0,
            "status_finish" => 0,
            "num" => 0,
            "need_num" => 0,
            "has_num" => 0,

            "remark" => $remark,
            "source_openid" => $source_openid,
            "verify_time" => $verify_time,
            "verify_openid" => $verify_openid,

            "birthday" => "1979-01-01",
            "gender" => $gender,
            "groups" => $groups,

            "cmzg_refund_status" => 0,
            "cmzg_refund_time" => "1979-01-01 00:00:00",

            'mch_id' => $mch_id,
            'api_v3_key' => $api_v3_key,
            'mch_serial_number' => $mch_serial_number,
            'private_key' => $private_key,
            'apiclient_cert' => $apiclient_cert,
            "pubkey_id" => $pubkey_id,
            "pubkey_pem" => $pubkey_pem
        ];
        $header = ['Content-Type: application/json'];
        $params_a = json_encode($params_a);
        Log::info("夏天抢购新订单：" . $params_a);
        if ($test == 'yes') {
            return $params_a;
        }
        $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
        return $http_data;
    }

    //根据PID找paychoice
    public function getpaychoicebypid($pid)
    {

        $api_url = "https://gateway.cmxz.com.cn/oa/api/platform/info";

        $params_a = [
            'pid' => $pid
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');

        //var_dump($http_data);
        //return;

        $jsonObject = json_decode($http_data);
        //var_dump($jsonObject);

        //$r['status'] = $jsonObject->data->pay_method->status;
        return $jsonObject->data->pay_method->status;
    }

    //根据paychoic找pid


    function curl_request2($url, $method = 'post', $params, $header, $type = 'http')
    {
        /**
         * 初始化curl，返回资源
         */
        $curl = curl_init($url);
        /**
         * 默认是get请求，如果是post/put请求，设置请求方式和请求参数
         */


        if (strtoupper($method) == 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params); // 这里传入的是 JSON 字符串
        } elseif (strtoupper($method) == 'GET') {
            // 对于 GET 请求，将参数拼接到 URL 后面
            if (!empty($params)) {
                $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($params);
            }
        }
        /**
         * 设置header头部传参
         */
        if (!empty($header)) {

            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        /**
         * 如果是HTTPS协议，禁止从服务器验证本地证书
         */
        if (strtoupper($type) == 'HTTPS') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        /**
         * 超时设置，单位毫秒
         */
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 10000);
        /**
         * 发送请求，返回结果
         */
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        /**
         * 不验证ssl
         */
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        /**
         * 选择地址
         * curl_setopt($curl,CURLOPT_URL,$url);
         */
        $res = curl_exec($curl);

        if ($res === false) {
            $error = curl_error($curl);
            curl_close($curl);
            // 抛出一个异常或返回错误信息
            throw new Exception("CURL Error: " . $error);
        }

        /**
         * 关闭请求
         */
        curl_close($curl);
        return $res;

    }


    public function findaidsbypid_rush(Request $request)
    {
        $pid = $request->get("pid"); //222
        $arr1 = $this->bigServiec_rush->findaidsbypid_rush($pid);
        return json_encode($arr1);
    }

    //lg备注 ：只有 （秒到账 和 每日提现的订单）老业务 才需要这个接口 也就是 paychoice = 1 【自收款】时千万别调 浪费
    //抢购
    public function findwqdifforder_rush(Request $request)
    {
        $dytid2 = $request->get("tid2");
        $tid2 = substr($dytid2, 1);
        $arr1 = $this->bigServiec_rush->findOrderBytid2_rush($tid2);
        //获取detailid
        $detailid = $arr1['detailid'];
        $arr2 = $this->bigServiec_rush->findRecordByxx_rush($detailid);
        $status_pay = $arr2['status']; //改成这个
        $params_a = [
            'nid' => "2" . $detailid,          //抢购
            "status_pay" => $status_pay,
        ];
        $header = ['Content-Type: application/json'];
        $params_a = json_encode($params_a);
        $header = ['Content-Type: application/json'];
        $xia_url = "https://gateway.cmxz.com.cn/oa/api/new/order/";
        $http_data = $this->curl_request2($xia_url, $method = 'put', $params_a, $header, $type = 'https');
        return $params_a;
    }


    //放到java项目 废弃
    public function samecopy_rush(Request $request)
    {
        $pid = $request->get("pid"); //53
        $aid = $request->get("aid"); //2323
        $phone = $request->get("phone");
        $password = $request->get("password");
        $uid = $request->get("uid");
        $tcode = $request->get("tcode");
        $cxcode10 = $request->get("tcode");
        $encryptedString = md5($phone . $password);
        if ($encryptedString !== $cxcode10) {
            //return "服务接口满";
        }
        $pid = 53;
        $aid = 9944;
        $uid = 6719;

        //调接口拷贝一个活动
        $url = " https://cm.cmzg.vip/app/index.php?i=" . $pid;
        $url .= "&c=entry&do=api_copy_theme&m=water_groupbuy3&themeid=" . $aid;
        $url .= "&uid=" . $uid;
        echo $url;

    }

    //合一起show_
    public function getpcbigr($ptarr)
    {
        $result = [];
        $arr1 = $this->bigservice->pcaids_totalfee($ptarr); //新版PC 根据aids 查排行
        // 遍历 themeid 从 1 到 6
        for ($i = 0; $i < count($ptarr); $i++) {
            $found = false;
            foreach ($arr1 as $item) {
                //if ($item['themeid'] == $i) {         超级BUG
                if ($item['themeid'] == $ptarr[$i]) {
                    $result[] = $item;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                // 如果没找到这个 themeid，则插入默认值
                $result[] = ['themeid' => $ptarr[$i], 'total_fee' => '0.00'];
            }
        }


        $arr2 = $this->bigservice->pcaids_commfee($ptarr); //新版PC 根据aids 查排行
        foreach ($result as &$item) {
            // 初始化一个标志位来检查是否找到了匹配的 comm_fee
            $foundCommFee = false;

            foreach ($arr2 as $commItem) {
                if ($item['themeid'] == $commItem['themeid']) {
                    $item['comm_fee'] = $commItem['comm_fee'];
                    $foundCommFee = true;
                    break; // 找到后退出循环以提高效率
                }
            }
            // 如果没有找到对应的 comm_fee，则设置为 "0.00"
            if (!$foundCommFee) {
                $item['comm_fee'] = '0.00';
            }
        }

        // arr3 数据（从 bigservice 获取）
        $arr3 = $this->bigservice->pcaids_other($ptarr);

// 遍历 $result，将 arr3 中的数据合并进去
        foreach ($result as &$item) {
            $found = false;

            foreach ($arr3 as $otherItem) {
                if ($item['themeid'] == $otherItem['themeid']) {
                    // 找到匹配项，添加字段
                    $item['total_paynum'] = $otherItem['total_paynum'];
                    $item['total_fanssum'] = $otherItem['total_fanssum'];
                    $item['total_scansum'] = $otherItem['total_scansum'];
                    $found = true;
                    break;
                }
            }

            // 如果没有找到对应项，填充默认值
            if (!$found) {
                $item['total_paynum'] = "0";
                $item['total_fanssum'] = "0";
                $item['total_scansum'] = "0";
            }
        }

        foreach ($result as &$item) {
            try {
                // 检查 total_fee 和 comm_fee 是否为有效的数值字符串
                if (!is_numeric($item['total_fee']) || !is_numeric($item['comm_fee'])) {
                    throw new InvalidArgumentException('Invalid numeric value for calculation.');
                }

                // 将 total_fee 和 comm_fee 转换为浮点数进行计算，并将结果保留两位小数
                $profit = number_format((floatval($item['total_fee']) - floatval($item['comm_fee'])), 2, '.', '');
                $item['profit'] = $profit;
            } catch (InvalidArgumentException $e) {
                // 处理无效参数异常，例如设置一个默认值或者记录错误日志
                error_log("Error calculating profit for themeid {$item['themeid']}: " . $e->getMessage());
                $item['profit'] = '0.00'; // 设置默认值
            } catch (Exception $e) {
                // 处理其他可能的异常
                error_log("Unexpected error calculating profit for themeid {$item['themeid']}: " . $e->getMessage());
                $item['profit'] = '0.00'; // 设置默认值
            }
        }

// 取消引用，避免后续对 $item 的意外修改
        unset($item);

        return $result;
    }

    public function getpcbigr_rush($qgarr)
    {
        $result_rush = [];
        $arr1_rush = $this->bigServiec_rush->pcaids_totalfee_rush($qgarr); //新版PC 根据aids 查排行

        //var_dump($arr1_rush);

        for ($i = 0; $i < count($qgarr); $i++) {
            $found = false;

            foreach ($arr1_rush as $item) {

                //if ($item['themeid'] == $i) {
                if ($item['themeid'] == $qgarr[$i]) {
                    $result_rush[] = $item;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                // 如果没找到这个 themeid，则插入默认值
                $result_rush[] = ['themeid' => $qgarr[$i], 'total_fee' => '0.00'];
            }
        }
        //return json_encode($arr1_rush);
        $arr2_rush = $this->bigServiec_rush->pcaids_commfee_rush($qgarr); //新版PC 根据aids 查排行
        foreach ($result_rush as &$item) {
            // 初始化一个标志位来检查是否找到了匹配的 comm_fee
            $foundCommFee = false;

            foreach ($arr2_rush as $commItem) {
                if ($item['themeid'] == $commItem['themeid']) {
                    $item['comm_fee'] = $commItem['comm_fee'];
                    $foundCommFee = true;
                    break; // 找到后退出循环以提高效率
                }
            }
            // 如果没有找到对应的 comm_fee，则设置为 "0.00"
            if (!$foundCommFee) {
                $item['comm_fee'] = '0.00';
            }
        }

        $arr3_rush = $this->bigServiec_rush->pcaids_other_rush($qgarr);
        foreach ($result_rush as &$item) {
            $found = false;

            foreach ($arr3_rush as $otherItem) {
                if ($item['themeid'] == $otherItem['themeid']) {
                    // 找到匹配项，添加字段
                    $item['total_paynum'] = $otherItem['total_paynum'];
                    $item['total_fanssum'] = $otherItem['total_fanssum'];
                    $item['total_scansum'] = $otherItem['total_scansum'];
                    $found = true;
                    break;
                }
            }

            // 如果没有找到对应项，填充默认值
            if (!$found) {
                $item['total_paynum'] = "0";
                $item['total_fanssum'] = "0";
                $item['total_scansum'] = "0";
            }
        }


        foreach ($result_rush as &$item) {
            if (!is_numeric($item['total_fee']) || !is_numeric($item['comm_fee'])) {
                throw new InvalidArgumentException('Invalid numeric value for calculation.');
            }

            // 将 total_fee 和 comm_fee 转换为浮点数进行计算，并将结果保留两位小数
            $profit = number_format((floatval($item['total_fee']) - floatval($item['comm_fee'])), 2, '.', '');
            $item['profit'] = $profit;
        }

        return $result_rush;
    }


    public function showptqg(Request $request)
    {
        $pt = $request->get('pt');
        $qg = $request->get('qg');
//        $pt = "1,2,3,4,5,6";  //合并不起来
//        $qg = "1,3,4,5,6,7"; //合并不起来
        $result = null;
        $result_rush = null;
        if (!empty($pt)) {
            $ptarr = explode(',', $pt);
            $ptarr = array_map('intval', $ptarr);
            $result = $this->getpcbigr($ptarr);
        }
        if (!empty($qg)) {
            $qgarr = explode(',', $qg);
            $qgarr = array_map('intval', $qgarr);
            $result_rush = $this->getpcbigr_rush($qgarr);
        }
        $needresult['pt'] = $result;
        $needresult['qg'] = $result_rush;
        return json_encode($needresult);

    }

    //findNpidbyoa_rush
    public function findpidaidforcopy($paytype, $plattype,$phone = 1)
    {
        //注意这个拼团的接口；因为要查 ims_water_salegroup3_theme 的case 案例活动; 所以plattype 肯定是1 【暂时没有备注】

        //这种默认值的写法;相当于帮助了调用方
        if($phone == 2){
            return 2; //测试
        }
        $oa_url = "https://gateway.cmxz.com.cn/oa/api/platforms/?format=json&page=1&pay_method={$paytype}&platform_type={$plattype}&platform_status=1";
        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($oa_url, $method = 'get', '', $header, $type = 'https');

        $a = json_decode($http_data);
        $data = $a->data;
        $pid = 0;
        $len1 = count($data);
        $pids = [];
        if ($len1 > 0) {
            foreach ($data as $e) {
                array_push($pids, $e->platform_id);
            }

            $pid = $data[0]->platform_id;
        } else {
            $result['has-api'] = '接口pid无数据';
        };
        $aid = 0;
//        if($pid !== 0 ){
//
//            $arr1 = $this->bigservice->findcasebypid($pid);
//            if(count($arr1) > 0 ){
//                $r = $arr1[0];  //随便取一个
//                //return $r['id'];
//                $aid = $r['id'];
//            }else{
//                //return '没用数据';
//                $result['has-message']='此pid 没有样例活动';
//
//            }
//        }

        //第一步 pids 再过滤一波; 找出这个账号下已经做过的活动的pids2  [53,99]
        //第二步 pids =[11,53,45,98,99]  pids2=[53,99]
        //第三步  再取交集 【53,99】
        $pids2 = [];
        if($phone != 1){
            //$pids = [54,56,93];
            $pids2 = $this->finddidpid_byphone_fun($phone);
            if(!empty($pids2)){
                $pids_result = array_intersect($pids, $pids2);
            }
            //合并出空      [54,56,93]   和   [5,12,15,43,53,67]   合并出空
            if(!empty($pids_result)){
                $pids = $pids_result;
            }else{
                //$pids 仍然是那个pids
            }

            //return json_encode($pids);
        }


        if (!empty($pids)) {
            $ini = 0;
            foreach ($pids as $item) {
                $arr1 = $this->bigservice->findcasebypid($item);
                $ini++;
                if (count($arr1) > 0) {
                    $r = $arr1[0];  //随便取一个
                    //return $r['id'];
                    $pid = $item;
                    $aid = $r['id'];
                    break;
                } else {
                    $result['has-message'] = '此pid 没有样例活动';
                }
            }
            $result['ini'] = $ini;
        } else {
            $result['msg'] = '夏天接口pids为空';
        }

        $result['pidssss'] = $pids;
        $result['pidssss2'] = $pids2;
        $result['len1'] = $len1;
        $result['pid'] = $pid;
        $result['aid'] = $aid;
        $result['arr1'] = $arr1;
        return json_encode($result);
    }


    public function finddidpid_byphone($phone)
    {
        $pids = $this->finddidpid_byphone_fun($phone);

        return json_encode($pids);
    }

    public function finddidpid_byphone_fun($phone){
        $arr1 = $this->bigservice->finddidpid_byphone($phone);
        //5个对象
        $pids=[];
        foreach ($arr1 as $key => $value) {
            // 执行操作，$key 是当前元素的键（或索引），$value 是当前元素的值
            array_push($pids,$value['uniacid']);
        }
        return $pids;
    }

    //finddidpid_byphone_fun_rush
    public function finddidpid_byphone_fun_rush($phone){
        $arr1 = $this->bigServiec_rush->finddidpid_byphone_rush($phone);
        //5个对象
        $pids=[];
        foreach ($arr1 as $key => $value) {
            // 执行操作，$key 是当前元素的键（或索引），$value 是当前元素的值
            array_push($pids,$value['uniacid']);
        }
        return $pids;
    }

    //抢购找pid夏天 和 aid 活动
    public function findpidaidforcopy_rush(Request $request)
    {

        //$paytype, $plattype,$phone = 1
        $paytype = $request->get("paytype"); //222
        $plattype = $request->get("plattype"); //222
        $tt =  $request->get("tt"); //222
        $phone =  $request->get("phone"); //222

        if($tt == 2){
            return $phone;
        }

        if($phone == 2){
            return 2; //测试
        }

        //return 11;
        //根据支付方式 和 平台 查一个pid(随机)
        //return $paytype.$plattype;

        //todo1 夏天的接口随机拿一个pid
        // 直接返回给 JAVA [投票项目]
        //例子
        //$oa_url = "https://gateway.cmxz.com.cn/oa/api/platforms/?format=json&page=1&pay_method=1&platform_type=2";
        $oa_url = "https://gateway.cmxz.com.cn/oa/api/platforms/?format=json&page=1&pay_method={$paytype}&platform_type={$plattype}&platform_status=1";
        $header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($oa_url, $method = 'get', '', $header, $type = 'https');

        $a = json_decode($http_data);
        $data = $a->data;
        $pid = 0;
        if (count($data) > 0) {
            $pid = $data[0]->platform_id;
        } else {
        };

        $len1 = count($data);
        $pids = [];
        if ($len1 > 0) {
            foreach ($data as $e) {
                array_push($pids, $e->platform_id);
            }

            $pid = $data[0]->platform_id;
        } else {
            $result['has-api'] = '接口pid无数据';
        };
        $aid = 0;

        //
        $pids2 = [];
        if(!empty($phone)){
            //$pids = [54,56,93];
            $pids2 = $this->finddidpid_byphone_fun_rush($phone);
            if(!empty($pids2)){
                $pids_result = array_intersect($pids, $pids2);
            }
            //合并出空      [54,56,93]   和   [5,12,15,43,53,67]   合并出空
            if(!empty($pids_result)){
                $pids = $pids_result;
            }else{
                //$pids 仍然是那个pids
            }

            //return json_encode($pids);
        }

        if (!empty($pids)) {
            $ini = 0;
            foreach ($pids as $item) {
                $arr1 = $this->bigServiec_rush->findcasebypid_rush($item);
                $ini++;
                if (count($arr1) > 0) {
                    $r = $arr1[0];  //随便取一个
                    //return $r['id'];
                    $pid = $item;
                    $aid = $r['id'];
                    break;
                } else {
                    $result['has-message'] = '此pid 没有样例活动';
                }

            }
            $result['ini'] = $ini;

        } else {
            $result['msg'] = '夏天接口pids为空';
        }


        $result['pid'] = $pid;
        $result['aid'] = $aid;
        $result['pidssss'] = $pids;
        $result['pidssss2'] = $pids2;
        return json_encode($result);
    }


    //根据夏天的pid 去找到是模板的活动。有很多哥 挑一个 $arr1
    public function findcasebypid_rush($pid)
    {
        $arr1 = $this->bigServiec_rush->findcasebypid_rush($pid);
        if (count($arr1) > 0) {
            $r = $arr1[0];  //随便取一个
            return $r['id'];
        } else {
            return '没用数据';
        }
    }







    //同步订单信息主要是支付信息 和 退款信息，  抢购没有拼团状态
    //新版PC 同步订单
    public function synorderbynid_rush($nid)
    {
        //新版detailid 就是新版订单id来查和更新
//        $dytid2 = $request->get("tid2");
//        $tid2 = substr($dytid2, 1);
//        $arr1 = $this->bigServiec_rush->findOrderBytid2_rush($tid2);
//        $detailid = $arr1['detailid'];
        $page_detailid = $nid;
        $db_detailid = substr($page_detailid, 1);

        $arr2 = $this->bigServiec_rush->findRecordByxx_rush($db_detailid);
        $status_pay = $arr2['status']; //改成这个
        $status_refund = $isrefund = $arr2['isrefund']; //是否退款要更新
        $refund_fee = 0; //抢购的需要查ims_water_groupbuy3_order 表。
        $billcode = $arr2['billcode'];


        //退款
        if (1 == $isrefund) {
            $arr1 = $this->bigServiec_rush->findOrderbybillcode_rush($billcode);
            $refund_fee = $arr1['refundfee'];
        }

        $cmzg_refund_status = 0;
        if (1 == $isrefund) {
            $cmzg_refund_status = 1; // 0,1,2（待处理,退款处理成功，驳回）  默认是0,申请了？ 
        }

        //退款很负责 例如。billcode 反查 订单ordersn
        $params_a = [
            'nid' => $nid,          //抢购
            "status_pay" => $status_pay,
            "status_refund" => $status_refund,
            "refund_fee" => $refund_fee,
            "cmzg_refund_status" => $cmzg_refund_status,
        ];

        $params_a = json_encode($params_a);
        $header = ['Content-Type: application/json'];
        $xia_url = "https://gateway.cmxz.com.cn/oa/api/new/order/";
        $http_data = $this->curl_request2($xia_url, $method = 'put', $params_a, $header, $type = 'https');
        return 1;
    }

    //测试入参方式的，可以工作
    public function tuu($gg, $kk)
    {
        return $gg . '--' . $kk;
    }

    //小卢要 手机号查 手机号查询支付配置信息的接口得先给我的
    //我有pid aid                  先拿到支付
    //我有 aid 实际根据 就能拿到 uid  就能拿到人

    //
    //拉起支付时 通过pid  aid 等到手机号
    //

    //小卢需要 手机号 查一个pid  aid
    // 有手机号


    //小卢分账需要的pid aid  以后PC配了就不用了
    public function findpidaidforfengbyphoneaid_rush($phone, $aid)
    {
        $arr1 = $this->bigServiec_rush->findpidaidforfengbyphone_1_rush($phone);
        $r['db1'] = $arr1;
        //return json_encode($arr1);
        if (count($arr1) > 0) {
            $row = $arr1[0];  //随便取一个
            $uid = $row['uid'];
            $arr2 = $this->bigServiec_rush->findpidaidforfengbyphone_3_rush($uid, $aid);
            $r['pid'] = $arr2[0]['uniacid'];
            $r['aid'] = $arr2[0]['id'];
            $r['db2'] = $arr2;
            $r['has'] = 'yes';
            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }
    }

    public function findpidaidforfengbyphone_rush($phone)
    {
        $arr1 = $this->bigServiec_rush->findpidaidforfengbyphone_1_rush($phone);
        $r['db1'] = $arr1;
        //return json_encode($arr1);
        if (count($arr1) > 0) {
            $row = $arr1[0];  //随便取一个
            $uid = $row['uid'];
            $arr2 = $this->bigServiec_rush->findpidaidforfengbyphone_2_rush($uid);
            $r['pid'] = $arr2[0]['uniacid'];
            $r['aid'] = $arr2[0]['id'];
            $r['db2'] = $arr2;
            return json_encode($r);
        } else {
            return '没用数据';
        }
    }

    public function phone3_rush($aid)
    {
        $arr1 = $this->bigServiec_rush->findphonebyaid_1_rush($aid);
        if (count($arr1) > 0) {
            $row = $arr1[0];   //一条 活动数据
            $uid = $row['uid'];
            $arr2 = $this->bigServiec_rush->findphonebyaid_2_rush($uid);
            if (count($arr2) > 0) {
                //$r['db']=$arr1;
                $r['phone'] = $arr2[0]['username'];
                $r['has'] = 'yes';
                return json_encode($r);
            }
            $r['has'] = 'no';
            return json_encode($r);
        } else {
            $r['has'] = 'no';
            return json_encode($r);
        }

    }

    //补充一个员工列表
    public function the_worklist_rush(Request $request)
    {
        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");

        $arr = $this->bigServiec_rush->the_worklist_rush($uniacid, $themeid);
        return json($arr);
    }


    public function getneworder_rush2(Request $request)
    {
        $tid2 = $request->get("tid2"); //222
        $dytid2 = $request->get("tid2"); //222
        $tid2 = substr($tid2, 1);
        $test = $request->get("test"); //222
        $paytype = $request->get("paytype", 999);
        $okfee = $request->get('okfree');
        try {

            if ($okfee == 'yes') {
                $shortorderid = $request->get('shortorderid');
                $arr1 = $this->bigServiec_rush->findOrderByShortid_rush($shortorderid);
                //return json_encode($arr1);
                //根据短的订单号来查订单
                $dytid2 = '3'; //丢了 用sn合适不
                $detailid = $shortorderid;

                //return json_encode($arr1);
            } else {
                $arr1 = $this->bigServiec_rush->findOrderBytid2_rush($tid2);
            }


            if (empty($arr1)) {
                echo 'no data1';
                return 'no data';
            } else {
                return json_encode($arr1);
            }


            $detailid = $arr1['detailid'];
            $uniacid = $arr1['uniacid'];
            $themeid = $arr1['themeid'];
            $avatar = $arr1['avatar'];
            $username = $arr1['username'];
            $nickname = $arr1['nickname'];
            $mobile = $arr1['mobile'];

            //return json_encode($arr1);

            $status_pay = $arr1['paystate'];
            // $refund_fee = $arr2['refund_fee'];  这个 抢购比较特别。拼团中取record 中的数据。但是抢购 要取订单的
            //id 就是 detailid
            //$arr2 = $this->bigServiec->findRecordByxx($detailid);
            $refund_fee = $arr1['refundfee'];  //先取了; 先弄个空看能不能插入;

            $arr2 = $this->bigServiec_rush->findRecordByxx_rush($detailid);


            $status_pay = $arr2['status']; //改成这个

            $billcode = $arr2['billcode'];
            $openid = $arr2['openid'];
            $fee = $arr2['fee'];
            $option = $arr2['option'];
            $option2 = $arr2['option2'];

            $note = $arr2['address'];
            $note2 = $arr2['datetime'];
            $f_openid = $arr2['fopenid'];
            $status_refund = $arr2['isrefund'];

            $add_time = $arr2['addtime'];
            $add_time = date("Y-m-d H:i:s", $add_time);
            $pay_time = $arr2['paytime'];
            $pay_time = date("Y-m-d H:i:s", $pay_time);

            $status_type = 0; //硬塞

            $remark = $arr2['remark'];
            $source_openid = $arr2['sourceid'];
            $verify_time = $arr2['verifytime'];
            $verify_time = date("Y-m-d H:i:s", $verify_time);
            $verify_openid = $arr2['verifyopenid'];
            $birthday = $arr2['birthday'];
            $gender = $arr2['gender'];
            if ($gender == '男生') {
                $gender = 1;
            } else {
                $gender = 2;
            }
            $groups = $arr2['groups'];

            //5月11号新增
            //$r = $this->getpaychoicebypid($uniacid); //2  支付方式
            if (999 == $paytype) {
                // 2025 6 8 前端打包后时必传的
                $r = $this->getpaychoicebypid($uniacid); //2  支付方式
            } else {
                $r = $paytype;
            }


            $mch_id = '';
            $api_v3_key = "";
            $mch_serial_number = "";
            $private_key = "";
            $apiclient_cert = "";

            if (1 == $r) {
                $lg = "no"; //自收款 不做处理

            } else {
                $lg = "yes"; //老业务。 每日 秒 代理
            }
            $url = 'https://gateway.cmxz.com.cn/oa/api/new/order/';
            $params_a = [
                'lg' => $lg,
                'nid' => "2" . $detailid,
                'dytid2' => $dytid2,

                'uniac_id' => $uniacid,
                'ntheme_id' => "2" . $themeid,
                "bill_code" => $billcode,
                "nickname" => $nickname,
                "avatar" => $avatar,
                "username" => $username,
                "mobile" => $mobile,
                "openid" => $openid,
                "fee" => $fee,
                "option" => $option,
                "option2" => $option2,

                "note" => $note,
                "note2" => $note2,
                "f_openid" => $f_openid,
                "status_refund" => $status_refund,
                "refund_fee" => $refund_fee,
                "status_pay" => $status_pay,

                "add_time" => $add_time,
                "pay_time" => $pay_time,

                "status_type" => $status_type, //身份
                "pid" => 0,
                "noid" => 0,
                "status_finish" => 0,
                "num" => 0,
                "need_num" => 0,
                "has_num" => 0,

                "remark" => $remark,
                "source_openid" => $source_openid,
                "verify_time" => $verify_time,
                "verify_openid" => $verify_openid,

                "birthday" => "1979-01-01",
                "gender" => $gender,
                "groups" => $groups,

                "cmzg_refund_status" => 0,
                "cmzg_refund_time" => "1979-01-01 00:00:00",

                'mch_id' => $mch_id,
                'api_v3_key' => $api_v3_key,
                'mch_serial_number' => $mch_serial_number,
                'private_key' => $private_key,
                'apiclient_cert' => $apiclient_cert

            ];
        } catch (Exception $e) {
            return $e;
        }

        $header = ['Content-Type: application/json'];
        $params_a = json_encode($params_a);
        if ($test == 'yes') {
            return $params_a;
        }
        $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
        return $http_data;
    }


    public function testfindboss_rush(Request $request)
    {
        $aid = $request->get("aid");
        $phone = $this->findboss_rush($aid);
        if ($phone == "") {
            return "手机号为空";
        }
        return $phone;
    }

    public function findboss_rush($aid)
    {
        $arr1 = $this->bigServiec_rush->findphonebyaid_1_rush($aid);
        if (count($arr1) > 0) {
            $row = $arr1[0];   //一条 活动数据
            $uid = $row['uid'];
            $arr2 = $this->bigServiec_rush->findphonebyaid_2_rush($uid);
            if (count($arr2) > 0) {
                return $arr2[0]['username'];
            }
        }
        return "";
    }

    public function findpaymsg($bossphone)
    {
        $params_a = [
            'bossphone' => $bossphone
        ];
        $params = json_encode($params_a);

        $header = ['Content-Type: application/json'];
//        $http_data = $this->curl_request2($api_url, $method = 'post', $params, $header, $type = 'https');

        $url = "https://back.smartshopkeeper.com/admin-api/cmzgMerchantPayConfig/queryBossFzConfig";
        $http_data = $this->curl_request2($url, $method = 'post', $params, $header, $type = "https");
        $jsonObject = json_decode($http_data);
        $data = $jsonObject->data;

        $mchId = $data->mchId;
        $apiV3Key = $data->apiV3Key;
        $privateKey = $data->privateKey;
        $apiclientCert = $data->apiclientCert;
        $mchSerialNumber = $data->mchSerialNumber;
        $pubkeyId = $data->pubkeyId;
        $pubkeyPem = $data->pubkeyPem;
        $payMode = $data->payMode;

        $r['mchId'] = $mchId;
        $r['apiV3kEY'] = $apiV3Key;
        $r['privateKey'] = $privateKey;
        $r['apiclientCert'] = $apiclientCert;
        $r['mchSerialNumber'] = $mchSerialNumber;
        $r['pubkeyId'] = $pubkeyId;
        $r['pubkeyPem'] = $pubkeyPem;
        $r['payMode'] = $payMode;
        return $r;
    }

    public function api_data_set(Request $request)
    {
        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $data = $request->get("data");
        $m = $request->get("m");
        $test =  $request->get("test");
        $url  = "https://cm.cmzg.vip/app/index.php?i=$pid&a=wxapp&c=entry&do=api_data_set&m=$m&themeid=$aid&data=$data";
        if("yes" == $test){
            return $url;
        }
        //$header = ['Content-Type: application/json'];
        $http_data = $this->curl_request2($url, $method = 'get', '', $header=[], $type = 'https');
        return $http_data;

    }

    //api_data_get
    public function api_data_get(Request $request)
    {
        $pid = $request->get("pid");
        $aid = $request->get("aid");
        $m = $request->get("m");
        $test =  $request->get("test");
        $openid = $request->get("openid");


        //$url  = "https://cm.cmzg.vip/app/index.php?i=$pid&a=wxapp&c=entry&do=api_data_get&m=$m&themeid=$aid";
        $url  = "https://cm.cmzg.vip/app/index.php?i=$pid&a=wxapp&openid=$openid&c=entry&do=api_data_get&m=$m&themeid=$aid";
        if("yes" == $test){
            return $url;
        }
        $http_data = $this->curl_request2($url, $method = 'get', '', $header=[], $type = 'https');

        return $http_data;

    }


    //todo 海报
    public function haibao_rush(Request $request)
    {

        $uniacid = $request->get("uniacid");
        $themeid = $request->get("themeid");
        $openid = $request->get('openid');
        //return "haibao_rush";

        //第一步 成功
        //https://back.screen.cmxz.com.cn/index.php/haibao_rush?uniacid=93&themeid=4989&openid=oBuMP7ZIBNU-CtyPGpnz8rdfjF74
        $arr_touxiang = $this->bigServiec_rush->findhaibao_touxiang_rush($uniacid, $themeid, $openid);
        $len = count($arr_touxiang['sqldata']);
        if ($len > 0) {
            $avatar_url = $arr_touxiang['sqldata'][0]['avatar'];
            //echo $avatar;
        }
        if (!isset($avatar_url)) {
            echo "DB没有头像";
        } else {
            //echo $avatar_url;
        }

        //第二步
        $arr_head = $this->bigServiec_rush->findhaibao_config_rush($uniacid, $themeid);
        $len2 = count($arr_head['sqldata']);
        if ($len2 > 0) {
            $value = $arr_head['sqldata'][0]['value'];
        }
        if (!isset($value)) {
            echo "DB活动配置没有";
        }
        $arr_value = unserialize($value);
        //return "ok";
        $headdb = $arr_value['headlogo'];
        $head_url = "https://tuan.cmzg.vip/" . $headdb;
        //return $head_url;
        //第三步

        $api_url = "https://cm.cmzg.vip/app/index.php?i=$uniacid&c=entry&themeid=$themeid&openid=$openid&do=api_qrcode&m=water_groupbuy3";

        $http_data = $this->curl_request($api_url, $method = 'get', $params = [], $header = [], $type = 'https');

        $jsonObject = json_decode($http_data);
        //print_r($jsonObject);
        //return "ok";
        $arr_message = $jsonObject->message;
        if ($arr_message->msg == "success") {  //Cannot use object of type stdClass as array
            //echo "http api 有二维码";
            $qrcode_url = $arr_message->qrcode;
        } else {
            echo "http api 没有二维码";
        }

        try {
            //$baseImageUrl = 'https://cm.cmzg.vip/addons/water_salegroup3/data/poster/24/5260/a0dce8b9e00d06b63bdedda266c80732.png';
            $baseImageUrl = $head_url;
            $overlayImageUrls = [
                //"https://tuan.cmzg.vip/images/water_salegroup3/20241107132339_5433906773_2964.jpeg", //头像
                $avatar_url,
                $qrcode_url
            ];

            $positions = [
                'bottom-left', //top-left改 bottom-left
//                'top-right',
                'bottom-right'
            ];
            // 调用服务方法
            $this->imageService->mergeMultipleImagesToBrowser2($baseImageUrl, $overlayImageUrls, $positions);
            // 返回图像数据
            //header("Content-Type: image/png; charset=utf-8");
            //echo $baseImageUrl;
            exit;
            // 获取缓冲区内容并清除缓冲区
            //$imageData = ob_get_clean();

        } catch (\Exception $e) {
            return json(['status' => 'error', 'message' => $e->getMessage()]);
        }


    }

    function curl_request($url, $method = 'get', $params = [], $header = [], $type = 'http')
    {
        /**
         * 初始化curl，返回资源
         */
        $curl = curl_init($url);
        /**
         * 默认是get请求，如果是post/put请求，设置请求方式和请求参数
         */
        if (strtoupper($method) == 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        }
        if (strtoupper($method) == 'PUT') {
            curl_setopt($curl, CURLOPT_PUT, true);
        }
        /**
         * 设置header头部传参
         */
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        }
        /**
         * 如果是HTTPS协议，禁止从服务器验证本地证书
         */
        if (strtoupper($type) == 'HTTPS') {
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        }
        /**
         * 超时设置，单位毫秒
         */
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 10000);
        /**
         * 发送请求，返回结果
         */
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        /**
         * 不验证ssl
         */
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        /**
         * 选择地址
         * curl_setopt($curl,CURLOPT_URL,$url);
         */
        $res = curl_exec($curl);

        if ($res === false) {
            $error = curl_error($curl);
            curl_close($curl);
            // 抛出一个异常或返回错误信息
            throw new Exception("CURL Error: " . $error);
        }

        /**
         * 关闭请求
         */
        curl_close($curl);
        return $res;

    }

    //  $http_data = $this->curl_request2($url, $method = 'post', $params_a, $header, $type = 'https');
    //todo 触发一下倒计时的插入数据
    public function timeorderflag(Request $request){
        //参数原样调一次
        $og = $request->post();
        $cmzgAid = $og['cmzgAid'];
        $cmzgPid = $og['cmzgPid'];
        $cmzgOrderid = $og['cmzgOrderid'];
        $cmzgFormid = $og['cmzgFormid'];
        $cmzgActivityType = $og['cmzgActivityType'];


        $params_a = [
            'cmzgAid' => $cmzgAid,
            'cmzgPid' => $cmzgPid,
            'cmzgOrderid' => $cmzgOrderid,
            'cmzgFormid' => $cmzgFormid,
            'cmzgActivityType' => $cmzgActivityType
        ];

        //回调控制器
//        $url = "http://192.168.2.212:48083/admin-api/pt/wnform/savetimeorder";
        $url = "https://back.smartshopkeeper.com/admin-api/admin-api/pt/wnform/savetimeorder";

        $header = ['Content-Type: application/json'];
        $params_a = json_encode($params_a);

        //$http_data = $this->curl_request2($url, $method = 'post',  $params_a, $header, $type = 'http');

        return $params_a;
    }

    //抢购退款
    public function oneordercx_rush(Request $request)
    {
        $detailid = $request->get("detailid");
        $arr = $this->bigServiec_rush->gettidby39like_rush($detailid);
        return json_encode($arr);
    }

    //manyshow_rush  多规格回显
    public function manyshow_rush(Request $request)
    {
        $uniacid = $request->get("pid");
        $themeid = $request->get("aid");

        $config_rush = $this->bigServiec_rush->findhaibao_config_rush($uniacid, $themeid);

        $len2 = count($config_rush['sqldata']);
        if ($len2 > 0) {
            $value = $config_rush['sqldata'][0]['value'];
        }
        if (!isset($value)) {
            echo "DB活动配置没有";
        }
        $arr_value = unserialize($value);
        //return "ok";
        $headdb = $arr_value['headlogo'];
        //echo $headdb;

        dump($arr_value);
    }


}
